package cn.lanchengkeji.datafillingsystem.controller;


import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.Roles;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.service.IMenuService;
import cn.lanchengkeji.datafillingsystem.service.IOperationService;
import cn.lanchengkeji.datafillingsystem.service.IRolesService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import cn.lanchengkeji.datafillingsystem.vo.RolesVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"角色 前端控制器"})
@RestController
@RequestMapping("/roles")
public class RolesController extends BaseController {
    // 日志
    private static Logger logger = LoggerFactory.getLogger(RolesController.class);

    @Resource
    private IRolesService iRolesService;

    @Resource
    private IUsersService iUsersService;
    @Resource
    private IMenuService iMenuService;
    @Resource
    private IOperationService iOperationService;


    /**
     * 查询角色：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查询角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectRoles", method = RequestMethod.POST)
    public ResponseBean selectRoles(
            @RequestBody Roles rolesParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        if (Utils.notEmpty(rolesParam.getId())) {

            // 查询单条角色
            Roles param = new Roles();
            param.setId(rolesParam.getId());
            Roles roles = iRolesService.selectOneRoles(param);
            return new ResponseBean(StatusCode.OK, roles);
        } else {
            // 管理端只查询管理员和管理端用户角色
            List<Roles> list = iRolesService.list();
            return new ResponseBean(StatusCode.OK, list);
         /*   // 查询全部角色（翻页查询）
            if(pageSize == 0){
                pageSize = Integer.MAX_VALUE;
            }

            RolesVO searchRoles = new RolesVO();
            searchRoles.setId(rolesParam.getId());
            if(Utils.notEmpty(rolesParam.getRoleName())){
                searchRoles.setRoleName(rolesParam.getRoleName());
            }

            Page<RolesVO> page = new Page(currentPage,pageSize);

            page = iRolesService.pageRoles(page,searchRoles);
            return new ResponseBean(StatusCode.OK, page);*/
        }
    }

    /**
     * 查询角色：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查询角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectRoles2", method = RequestMethod.POST)
    public ResponseBean selectRoles2(
            @RequestBody Roles rolesParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        if (Utils.notEmpty(rolesParam.getId())) {

            // 查询单条角色
            Roles param = new Roles();
            param.setId(rolesParam.getId());
            Roles roles = iRolesService.selectOneRoles(param);
            return new ResponseBean(StatusCode.OK, roles);
        } else {

            // 查询全部角色（翻页查询）
            if (pageSize == 0) {
                pageSize = Integer.MAX_VALUE;
            }

            RolesVO searchRoles = new RolesVO();
            searchRoles.setId(rolesParam.getId());
            if (Utils.notEmpty(rolesParam.getRoleName())) {
                searchRoles.setRoleName(rolesParam.getRoleName());
            }

            Page<RolesVO> page = new Page(currentPage, pageSize);

            page = iRolesService.pageRoles(page, searchRoles);
            return new ResponseBean(StatusCode.OK, page);
        }

    }

    /**
     * 查询角色：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查询角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/viewRoles", method = RequestMethod.POST)
    public ResponseBean viewRoles() throws Exception {

        // 管理端只查询管理员和管理端用户角色
        List<Roles> list = iRolesService.list();
        return new ResponseBean(StatusCode.OK, list);
    }

    /**
     * 查询角色：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据用户查询角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectRolesByUser", method = RequestMethod.POST)
    public ResponseBean selectRolesByUser(
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);
        Users users = iUsersService.getUserByName(obj.toString());
        List<Roles> rolesList = iRolesService.list();
        List<Roles> returnList = new ArrayList<>();
        List<Roles> userRoles = iRolesService.getRolesByUser(users.getId());
        for (Roles roles : userRoles) {
            if (roles.getRoleName().equals("系统管理员")) {
                returnList.addAll(rolesList);
            } else if (roles.getRoleName().equals("市公司-管理员")) {
                for (Roles subRoles : rolesList) {
                    if (!subRoles.getRoleName().equals("系统管理员")) {
                        returnList.add(subRoles);
                    }
                }
            } else if (roles.getRoleName().equals("区县公司-管理员")) {
                for (Roles subRoles : rolesList) {
                    if (subRoles.getRoleName().equals("区县公司-管理员")
                            || subRoles.getRoleName().equals("区县公司-浏览用户")
                            || subRoles.getRoleName().equals("所客服中心")) {
                        returnList.add(subRoles);
                    }
                    returnList.add(subRoles);
                }
            }
        }
        return new ResponseBean(StatusCode.OK, returnList);
    }

    /**
     * 根据角色id查询用户
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据角色id查询用户", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectUsersByRoleId", method = RequestMethod.POST)
    public ResponseBean selectRoles(
            @RequestBody Roles rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        List<Users> usersList = iUsersService.selectUsersByRoleId(rolesParam.getId());
        return new ResponseBean(StatusCode.OK, usersList);
    }

    /**
     * 根据角色id查询菜单
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据角色id查询菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectMenusByRoleId", method = RequestMethod.POST)
    public ResponseBean selectMenusByRoleId(
            @RequestBody Roles rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        return new ResponseBean(StatusCode.OK, iMenuService.selectMenusByRoleId(rolesParam.getId()));
    }

    /**
     * 根据角色id查询操作权限
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据角色id查询操作权限", notes = "登陆才能操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "Integer", paramType = "query", required = true),
    })
    @RequiresAuthentication
    @RequiresPermissions("roles:view")
    @RequestMapping(value = "/selectOperationsByRoleId", method = RequestMethod.POST)
    public ResponseBean selectOperationsByRoleId(
            @RequestBody Roles rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        return new ResponseBean(StatusCode.OK, iOperationService.selectOperationsByRoleId(rolesParam.getId()));
    }


    /**
     * 添加角色，登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:create")
    @RequestMapping(value = "/insertRoles", method = RequestMethod.POST)
    public ResponseBean insertRoles(
            HttpServletRequest request,
            @RequestBody RolesVO rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "添加角色", userId, "新增");

        // 插入角色
        RolesVO roles = new RolesVO();

        if (Utils.notEmpty(rolesParam.getRoleName())) {
            roles.setRoleName(rolesParam.getRoleName());
        }
        if (Utils.notEmpty(rolesParam.getUserIdList())) {
            roles.setUserIdList(rolesParam.getUserIdList());
        }
        if (Utils.notEmpty(rolesParam.getMenuIdList())) {
            roles.setMenuIdList(rolesParam.getMenuIdList());
        }
        if (Utils.notEmpty(rolesParam.getOperationIdList())) {
            roles.setOperationIdList(rolesParam.getOperationIdList());
        }
        return iRolesService.insertRoles(roles);
    }


    /**
     * 修改角色，登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:edit")
    @RequestMapping(value = "/updateRoles", method = RequestMethod.POST)
    public ResponseBean updateRoles(
            HttpServletRequest request,
            @RequestBody RolesVO rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "修改角色", userId, "修改");

        // 修改角色
        RolesVO roles = new RolesVO();

        if (Utils.notEmpty(rolesParam.getRoleName())) {
            roles.setRoleName(rolesParam.getRoleName());
        }

        if (Utils.notEmpty(rolesParam.getId())) {
            roles.setId(rolesParam.getId());
        }

        if (Utils.notEmpty(rolesParam.getUserIdList())) {
            roles.setUserIdList(rolesParam.getUserIdList());
        }
        if (Utils.notEmpty(rolesParam.getMenuIdList())) {
            roles.setMenuIdList(rolesParam.getMenuIdList());
        }
        if (Utils.notEmpty(rolesParam.getOperationIdList())) {
            roles.setOperationIdList(rolesParam.getOperationIdList());
        }
        return iRolesService.updateRoles(roles);
    }

    /**
     * 删除角色，登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除角色", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("roles:delete")
    @RequestMapping(value = "/deleteRoles", method = RequestMethod.POST)
    public ResponseBean deleteRoles(
            HttpServletRequest request,
            @RequestBody Roles rolesParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "删除角色", userId, "删除");

        // 插入角色
        RolesVO roles = new RolesVO();
        roles.setId(rolesParam.getId());

        return iRolesService.deleteRoles(roles);
    }

}
